package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.AnYiRongApisUtil;
import com.block.datapush.service.apipush.utils.XinHuaUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 新花钱包  双授权
 */
@Service
public class XinHuaApisMaskPushService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String serialNo = UUID.randomUUID().toString();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("md5Phone", memberSourceInfo.getMobileMd5().toLowerCase());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("location", memberSourceInfo.getProvince()+","+memberSourceInfo.getCity());
        bizMap.put("loanLimit", XinHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("monthlyIncome", XinHuaUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("businessOwners", "无");
        bizMap.put("loanLongTime", XinHuaUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("creditSituation", XinHuaUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("openRedit", XinHuaUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("socialInsurance", XinHuaUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFund", XinHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("houseProperty", XinHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carProperty", XinHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("zmScore", XinHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("openSpendBai", "有");
        bizMap.put("openJdbt", "有");
        bizMap.put("education", XinHuaUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("occupation", XinHuaUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("businessInsurance", XinHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));

        long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(channelCode+"&"+timestamp+"&"+ apiSecret);
        String content = XinHuaUtil.encrypt(JSON.toJSONString(bizMap), apiSecret);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel",channelCode);
        paramMap.put("content",content);
        paramMap.put("timestamp",timestamp);
        paramMap.put("sign",sign);

        log.info("【薪花钱包下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【薪花钱包下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals("0",code)) {
            String name = resultObject.getString("productName");
            String institutionName = resultObject.getString("companyName");
            // 撞库成功之后，商户的机构数据存储

            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo",serialNo);
            infoObject.put("productId",serialNo);
            infoObject.put("productName",name);
            infoObject.put("companyName",institutionName);
            infoObject.put("companyLogo","https://anyirong-1325413174.cos.ap-nanjing.myqcloud.com/merchantlogo/58de21f8c94c4b0faa2746d0c9e91f5c图片1.png");
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = resultObject.getJSONArray("protocolList");
            for (int i=0;i<protocolList.size();i++){
                JSONObject jsonObject = new JSONObject();
                String protocolName = protocolList.getJSONObject(i).getString("protocolName");
                String protocolUrl = protocolList.getJSONObject(i).getString("protocolUrl");
                jsonObject.put("protocalName",protocolName);
                jsonObject.put("protocalUrl",protocolUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price = resultObject.getString("price");
                BigDecimal price1 = new BigDecimal(price);//下游返回分润后价格
                if (price1.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price1.multiply(typeRate);//分润前价格
                pushApiResult.setPrice(price1);
                pushApiResult.setPriceRight(priceLeft);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(serialNo);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("realPhone", memberSourceInfo.getMobile());
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("location", memberSourceInfo.getProvince()+","+memberSourceInfo.getCity());
        bizMap.put("loanLimit", XinHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("monthlyIncome", XinHuaUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("businessOwners", "无");
        bizMap.put("loanLongTime", XinHuaUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("creditSituation", XinHuaUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("openRedit", XinHuaUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("socialInsurance", XinHuaUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFund", XinHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("houseProperty", XinHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carProperty", XinHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("zmScore", XinHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("openSpendBai", "有");
        bizMap.put("openJdbt", "有");
        bizMap.put("education", XinHuaUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("occupation", XinHuaUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("businessInsurance", XinHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));

        long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(channelCode+"&"+timestamp+"&"+ apiSecret);
        String content = XinHuaUtil.encrypt(JSON.toJSONString(bizMap), apiSecret);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel",channelCode);
        paramMap.put("content",content);
        paramMap.put("timestamp",timestamp);
        paramMap.put("sign",sign);

        log.info("【薪花钱包下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【薪花钱包下游双授权】导单结束【result】{}", resultObject.toJSONString());

        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals("0",code)){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals("0",code)) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
